import { PlusOutlined } from '@ant-design/icons';
import { Button, Drawer, FormInstance, message, Popconfirm } from 'antd';
import React, { useRef, useState } from 'react';
import { FooterToolbar, PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  ModalForm,
  ProFormDependency,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProFormTreeSelect,
} from '@ant-design/pro-form';
import ProDescriptions, { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import {
  addRecognize,
  getRecognize,
  loadDictSelect,
  loadRecognize,
  removeRecognize,
  updateRecognize,
} from './service';
import type { RecognizeListItem, RecognizeListPagination } from './data';
import { loadOrgSelect } from '@/pages/Enterprise/Org/service';
import { loadPostSelect } from '@/pages/Enterprise/Post/service';
import { loadEmployeeSelect } from '@/pages/Employee/List/service';
import styles from './index.less';
import CheckModule from '@/components/CheckModule';

/**
 * 新增或更新辨识信息
 *
 * @param fields
 */

const handleAdd = async (fields: RecognizeListItem, mode: boolean) => {
  const hide = message.loading(mode ? '正在保存' : '正在添加');
  try {
    mode ? await updateRecognize({ ...fields }) : await addRecognize({ ...fields });
    hide();
    message.success(mode ? '保存成功' : '添加成功');
    return true;
  } catch (error) {
    // hide();
    // message.error(mode ? '保存失败请重试' : '添加失败请重试');
    return false;
  }
};
/**
 * 删除辨识
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows: RecognizeListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeRecognize(selectedRows.map((row) => row.recognizeId));
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const oddsData = {
  1: {
    text: '极低',
  },
  2: {
    text: '低',
  },
  4: {
    text: '中等',
  },
  7: {
    text: '高',
  },
  10: {
    text: '极高',
  },
};
const severityLevelData = {
  1: {
    text: '不严重',
  },
  2: {
    text: '较严重',
  },
  5: {
    text: '严重',
  },
  10: {
    text: '特别严重',
  },
};
const riskLevelData = {
  1: {
    text: '较小',
    color: '#0000FF',
  },
  2: {
    text: '一般',
    color: '#E1E13A',
  },
  3: {
    text: '较大',
    color: '#FFA500',
  },
  4: {
    text: '重大',
    color: '#FF0000',
  },
};
const hierarchyData = {
  1: {
    text: '公司级',
    color: '#FF0000',
  },
  2: {
    text: '部门级',
    color: '#FFA500',
  },
  3: {
    text: '班组级',
    color: '#E1E13A',
  },
  4: {
    text: '岗位级',
    color: '#0000FF',
  },
};
const frequencyData = {
  1: {
    text: '每日一次',
  },
  2: {
    text: '每周一次',
  },
  3: {
    text: '每月一次',
  },
  4: {
    text: '每季度一次',
  },
  5: {
    text: '每年一次',
  },
  6: {
    text: '每半年一次',
  },
};

const requestOrg = async () => {
  return loadOrgSelect({ status: '0' }).then(({ data }) => {
    return data;
  });
};
const requestPost = async () => {
  return loadPostSelect().then(({ data }) => {
    return data;
  });
};
const requestEmployee = async (param: any) => {
  return loadEmployeeSelect(param).then(({ data }) => {
    return data;
  });
};

const RecognizePage: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [currentRow, setCurrentRow] = useState<RecognizeListItem>();
  const [selectedRowsState, setSelectedRows] = useState<RecognizeListItem[]>([]);
  const columns: ProColumns<RecognizeListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionRef?.current?.pageInfo?.current || 1) - 1) *
                (actionRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '作业位置场所',
      dataIndex: 'place',
    },
    {
      title: '危险源',
      dataIndex: 'source',
      render: (_, record) => <span style={{ whiteSpace: 'pre-wrap' }}>{record?.measure}</span>,
    },
    {
      title: '管控措施',
      dataIndex: 'measure',
      render: (_, record) => <span style={{ whiteSpace: 'pre-wrap' }}>{record?.measure}</span>,
    },
    {
      title: '可能性大小L',
      dataIndex: 'odds',
      request: async () => {
        return loadDictSelect('sc_recognize_odds').then(({ data }) => {
          return data;
        });
      },
      valueEnum: oddsData,
    },
    {
      title: '结果严重程度C',
      dataIndex: 'severityLevel',
      valueEnum: severityLevelData,
    },
    {
      title: '风险等级',
      dataIndex: 'riskLevel',
      valueEnum: riskLevelData,
    },
    {
      title: '管控层级',
      dataIndex: 'hierarchy',
      valueEnum: hierarchyData,
    },
    {
      title: '辨识频次',
      dataIndex: 'frequency',
      valueEnum: frequencyData,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: false,
      valueEnum: {
        0: {
          text: '待审核',
          status: 'Default',
        },
        1: {
          text: '启用',
          status: 'Success',
        },
        2: {
          text: '禁用',
          status: 'Error',
        },
      },
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInDescriptions: true,
      render: (_, record) => [
        <a
          key="view"
          onClick={() => {
            setCurrentRow(record);
            setShowDetail(true);
          }}
        >
          查看
        </a>,
        <a
          key="edit"
          onClick={() => {
            formRef.current?.resetFields();
            setCurrentRow(record);
            setEditMode(true);
            handleModalVisible(true);
          }}
        >
          编辑
        </a>,

        <Popconfirm
          key="delete"
          okButtonProps={{ danger: true }}
          title={`确认删除辨识数据?`}
          onConfirm={async () => {
            setCurrentRow(record);
            await handleRemove([record]);
            actionRef.current?.reloadAndRest?.();
          }}
          okText="删除"
          cancelText="取消"
        >
          <a href="#"> 删除 </a>
        </Popconfirm>,
      ],
    },
  ];
  const [editMode, setEditMode] = useState<boolean>(false);

  return (
    <CheckModule code={'SC'}>
      <PageContainer waterMarkProps={{ content: '' }}>
        <ProTable<RecognizeListItem, RecognizeListPagination>
          headerTitle="辨识列表"
          actionRef={actionRef}
          rowKey="recognizeId"
          search={{
            labelWidth: 120,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                setEditMode(false);
                handleModalVisible(true);
              }}
            >
              <PlusOutlined /> 新建
            </Button>,
          ]}
          request={loadRecognize}
          columns={columns}
          rowSelection={{
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows);
            },
          }}
        />
        {selectedRowsState?.length > 0 && (
          <FooterToolbar
            extra={
              <div>
                已选择{' '}
                <a
                  style={{
                    fontWeight: 600,
                  }}
                >
                  {selectedRowsState.length}
                </a>{' '}
                个辨识
              </div>
            }
          >
            <Popconfirm
              key="delete"
              title={`确认删除选中的${selectedRowsState.length}个辨识?`}
              okButtonProps={{ danger: true }}
              onConfirm={async () => {
                await handleRemove(selectedRowsState);
                setSelectedRows([]);
                actionRef.current?.reloadAndRest?.();
              }}
              okText="删除"
              cancelText="取消"
            >
              <Button danger>批量删除</Button>
            </Popconfirm>
            {/*<Button type="primary">批量审批</Button>*/}
          </FooterToolbar>
        )}
        <ModalForm<RecognizeListItem>
          title={currentRow?.recognizeId || 0 > 0 ? '编辑辨识' : '新建辨识'}
          // width="600px"
          modalProps={{destroyOnClose: true, maskClosable: false}}
          layout={'horizontal'}
          labelCol={{ span: 5 }}
          wrapperCol={{ pull: 1, offset: 1, span: 17 }}
          formRef={formRef}
          // size={"large"}
          visible={createModalVisible}
          onValuesChange={(f, v) => {
            if (f.hasOwnProperty('orgId') || f.hasOwnProperty('postId')) {
              formRef.current?.setFieldsValue({ employeeId: undefined });
            }
            if (
              (f.hasOwnProperty('odds') || f.hasOwnProperty('severityLevel')) &&
              v.odds &&
              v.severityLevel
            ) {
              let riskValue = v.odds * v.severityLevel;
              let riskLevel = undefined;
              let hierarchy = undefined;

              if (riskValue > 55) {
                riskLevel = '4';
                hierarchy = '1';
              } else if (riskValue > 20) {
                riskLevel = '3';
                hierarchy = '2';
              } else if (riskValue > 5) {
                riskLevel = '2';
                hierarchy = '3';
              } else if (riskValue > 0) {
                riskLevel = '1';
                hierarchy = '4';
              }
              formRef.current?.setFieldsValue({
                riskValue: riskValue,
                riskLevel: riskLevel,
                hierarchy: hierarchy,
              });
            }
          }}
          onVisibleChange={(visible) => {
            if (!visible) {
              setCurrentRow(undefined);
            }
            handleModalVisible(visible);
          }}
          onFinish={async (value) => {
            const success = await handleAdd(value, editMode);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          request={(params) => {
            if (params.recognizeId > 0) {
              return getRecognize(params).then(({ data }) => {
                return data;
              });
            } else {
              return new Promise<RecognizeListItem>((resolve) => {
                resolve({ recognizeId: 0 });
              });
            }
          }}
          params={{ ...currentRow }}
        >
          <ProFormText hidden name="recognizeId" />
          <ProFormSelect
            name="postId"
            label={'责任岗位'}
            rules={[{ required: true }]}
            request={requestPost}
            disabled={editMode}
            fieldProps={{
              placeholder: '请选择责任岗位',
              dropdownMatchSelectWidth: false,
            }}
          />
          <ProFormTreeSelect
            name="orgId"
            label={'责任部门'}
            request={requestOrg}
            tooltip={'责任部门可以限定到部门对应的的岗位'}
            disabled={editMode}
            fieldProps={{
              placeholder: '请选择部门',
              treeDefaultExpandAll: true,
              treeLine: true,
              fieldNames: { label: 'label', value: 'id', children: 'children' },
            }}
          />

          <ProFormDependency name={['postId', 'orgId']}>
            {({ postId, orgId }) => {
              if (postId || orgId) {
                return (
                  <ProFormSelect
                    name="employeeId"
                    label={'责任人'}
                    tooltip={'可以将辨识限定到对应的人员'}
                    disabled={editMode}
                    request={requestEmployee}
                    params={{ postId, orgId }}
                    fieldProps={{
                      placeholder: '请选择责任岗位',
                      dropdownMatchSelectWidth: false,
                    }}
                  />
                );
              }
              return null;
            }}
          </ProFormDependency>

          {/*<ProFormSelect name="orgId" label={"责任人"} request={requestOrg} fieldProps={{*/}
          {/*  placeholder: "请选择部门",*/}
          {/*  treeDefaultExpandAll: true,*/}
          {/*  treeLine: true,*/}
          {/*  fieldNames: {label: 'label', value: 'id', children: 'children'},*/}
          {/*}}/>*/}
          <ProFormText rules={[{ required: true }]} label={'作业位置场所'} name="place" />
          <ProFormText label={'典型风险事件'} name="typicalCase" />
          <ProFormTextArea rules={[{ required: true }]} label={'危险源'} name="source" />
          <ProFormTextArea rules={[{ required: true }]} label={'现有管控措施'} name="measure" />
          <ProFormSelect
            rules={[{ required: true }]}
            label={'可能性大小L'}
            name="odds"
            valueEnum={oddsData}
          />
          <ProFormSelect
            rules={[{ required: true }]}
            label={'结果严重程度C'}
            name="severityLevel"
            valueEnum={severityLevelData}
          />

          <ProFormDependency name={['odds', 'severityLevel']}>
            {({ odds, severityLevel }) => {
              let riskLevel = '';
              let riskColor = { '4': '#FF0000', '3': '#FFA500', '2': '#E1E13A', '1': '#0000FF' };
              let hierarchyColor = {
                '1': '#FF0000',
                '2': '#FFA500',
                '3': '#E1E13A',
                '4': '#0000FF',
              };
              if (odds && severityLevel) {
                let riskValue = odds * severityLevel;
                if (riskValue > 55) {
                  riskLevel = '4';
                } else if (riskValue > 20) {
                  riskLevel = '3';
                } else if (riskValue > 5) {
                  riskLevel = '2';
                } else if (riskValue > 0) {
                  riskLevel = '1';
                }
              }
              console.log(styles['riskValue' + riskLevel]);
              // formRef.current?.setFieldsValue({"riskValue": odds * severityLevel});
              return (
                <span className={'sdafdsa'}>
                  <ProFormText
                    rules={[{ required: true }]}
                    label={'风险值D'}
                    name="riskValue"
                    fieldProps={{ className: styles['riskValue' + riskLevel] }}
                  />
                  <ProFormSelect
                    rules={[{ required: true }]}
                    label={'风险等级'}
                    name="riskLevel"
                    className={'8327489237498dkjsf'}
                    fieldProps={{
                      optionLabelProp: 'children',
                      optionItemRender(item) {
                        return <span style={{ color: riskColor[item.value] }}>{item.label}</span>;
                      },
                    }}
                    valueEnum={riskLevelData}
                  ></ProFormSelect>
                  <ProFormSelect
                    rules={[{ required: true }]}
                    label={'管控级别'}
                    name="hierarchy"
                    fieldProps={{
                      optionLabelProp: 'children',
                      optionItemRender(item) {
                        return (
                          <span style={{ color: hierarchyColor[item.value] }}>{item.label}</span>
                        );
                      },
                    }}
                    valueEnum={hierarchyData}
                  />
                </span>
              );

              // return <pre>
              //   <code>{odds * severityLevel}</code>
              // </pre>
            }}
          </ProFormDependency>

          <ProFormSelect
            rules={[{ required: true }]}
            label={'管控频次'}
            name="frequency"
            valueEnum={frequencyData}
            disabled={editMode}
          />
          <ProFormSelect
            rules={[{ required: true }]}
            label={'状态'}
            name="status"
            valueEnum={{
              1: {
                text: '启用',
                status: 'Success',
              },
              2: {
                text: '禁用',
                status: 'Error',
              },
            }}
          />
        </ModalForm>

        <Drawer
          width={800}
          visible={showDetail}
          onClose={() => {
            setCurrentRow(undefined);
            setShowDetail(false);
          }}
          closable={false}
        >
          {currentRow?.place && (
            <ProDescriptions<RecognizeListItem>
              column={1}
              bordered={true}
              title={currentRow?.place}
              request={getRecognize}
              layout={'horizontal'}
              params={currentRow}
              columns={columns as ProDescriptionsItemProps<RecognizeListItem>[]}
            />
          )}
        </Drawer>
      </PageContainer>
    </CheckModule>
  );
};

export default RecognizePage;
